package com.dongbo.recorder.screenrecord.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.os.Binder;
import android.os.Build;
import android.os.HandlerThread;
import android.os.IBinder;

import com.dongbo.recorder.screenrecord.utils.eventbus.EventBusUtils;
import com.dongbo.recorder.screenrecord.utils.eventbus.EventMessage;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.contents.Contents;
import com.dongbo.recorder.screenrecord.ui.activity.MainActivity;
import com.dongbo.recorder.screenrecord.utils.FileUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description:
 * @Author: gstory0404@gmail
 * @CreateDate: 2020/4/30 10:00
 */
public class RecordService extends Service {
    private MediaProjection mediaProjection;
    private MediaRecorder mediaRecorder;
    private VirtualDisplay virtualDisplay;

    private boolean running;
    private int width = 720;
    private int height = 1080;
    private int dpi;

    private String path;

    //定时器
    private Disposable disposable;
    private long recordTime = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return new RecordBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread serviceThread = new HandlerThread("service_thread",
                android.os.Process.THREAD_PRIORITY_BACKGROUND);
        serviceThread.start();
        running = false;
    }

    public String getpath() {
        return path;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void setMediaProject(MediaProjection project) {
        mediaProjection = project;
    }

    public boolean isRunning() {
        return running;
    }

    public void setConfig(int width, int height, int dpi) {
        this.width = width;
        this.height = height;
        this.dpi = dpi;
    }

    public boolean startRecord() {
        if (mediaProjection == null || running) {
            return false;
        }
        createRecorder();
        createVirtualDispla();
        try {
            mediaRecorder.start();
        } catch (IllegalStateException e) {
        }
        running = true;
        startTimer();
        return true;
    }

    public boolean stopRecord() {
        if (!running) {
            return false;
        }

        //开始结束时间间隔太短会报关闭失败bug
        mediaRecorder.setOnErrorListener(null);
        mediaRecorder.setOnInfoListener(null);
        mediaRecorder.setPreviewDisplay(null);

        running = false;

        try {
            mediaRecorder.stop();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaRecorder.reset();
        virtualDisplay.release();
        mediaProjection.stop();
        clearNotification();
        stopTimer();
        return true;
    }

    private void createRecorder() {
        mediaRecorder = new MediaRecorder();
        path = FileUtils.getScreenRecordFile() + AppLpds.getMySp().getVoice() + "x" + System.currentTimeMillis() + ".mp4";
        //        Log.d("声音---->", AppLpds.getMySp().getVoice() + "");
        if (AppLpds.getMySp().getVoice() == 1) {
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        }
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mediaRecorder.setVideoSize(width, height);
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //竖屏
        if (AppLpds.getMySp().getDirection() == 0) {
            mediaRecorder.setVideoSize(width, height);
            mediaRecorder.setOrientationHint(0);
            //横屏
        } else {
            mediaRecorder.setVideoSize(height, width);
            mediaRecorder.setOrientationHint(90);
        }

        if (AppLpds.getMySp().getVoice() == 1) {
//            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        }
        try {
            mediaRecorder.setOutputFile(path);
        } catch (IllegalStateException e) {
//            Log.v("gstory---->", "==" + e.getMessage());
        }
        mediaRecorder.setVideoFrameRate(60);
        //横竖屏
//        mediaRecorder.setOrientationHint(90);
        switch (AppLpds.getMySp().getDefinitiont()) {
            case 0:
                mediaRecorder.setVideoEncodingBitRate(900 * 1024);
                break;
            case 1:
                mediaRecorder.setVideoEncodingBitRate(4 * 1024 * 1024);
                break;
            case 2:
                mediaRecorder.setVideoEncodingBitRate(10 * 1024 * 1024);
                break;
        }
//        Log.v("gstory---->", AppLpds.getMySp().getDirection() + "--");
        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
//            Log.v("gstory---->", e.toString());
            e.printStackTrace();
        }
    }

    private void createVirtualDispla() {
        if (AppLpds.getMySp().getDirection() == 0) {
            virtualDisplay = mediaProjection.createVirtualDisplay("MainScreen", width, height, dpi,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
        } else {
            virtualDisplay = mediaProjection.createVirtualDisplay("MainScreen", height, width, dpi,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
        }
    }

    public class RecordBinder extends Binder {
        public RecordService getRecordService() {
            return RecordService.this;
        }
    }

    public void createNotificationChannel() {
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class); //点击后跳转的界面，可以设置跳转数据

        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                //.setContentTitle("SMI InstantView") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("正在录屏") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        /*以下是对Android 8.0的适配*/
        //普通notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id");
        }
        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        //前台服务notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
//            notificationManager.notify("mytext",ID_NOTIFICATION,notification);
        }
        startForeground(1, notification);
    }

    //删除通知
    public void clearNotification() {
        stopForeground(true);
    }

    //开始计时
    private void startTimer() {
        // 每隔秒执行一次逻辑代码
        disposable = Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Long aLong) throws Exception {
                        recordTime = recordTime + 1000;
                        EventBusUtils.post(new EventMessage<>(Contents.EventType.TAG_RECORD_DATE, recordTime));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    //结束计时
    protected void stopTimer() {
        recordTime = 0;
        if (null != disposable) {
            disposable.dispose();
            disposable = null;
        }
    }

//    public void setartActivity() {
//        Log.v("gstory","到这里");
//        Intent dialogIntent = new Intent(getBaseContext(), TextActivity.class);
//        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        getApplication().startActivity(dialogIntent);
//    }
}
